package mygang.controller.manager;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mygang.controller.AbstractController;
import mygang.helper.JsonHelper;
import mygang.helper.Utils;
import mygang.model.constructor.field.Field;
import mygang.model.constructor.field.FieldTemplate;
import mygang.service.manager.EntityService;
import mygang.service.manager.FieldService;
import mygang.service.manager.FieldTemplateService;
import mygang.service.manager.TableService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 */
@Controller
@RequestMapping(AbstractController.MANAGE_FIELD)
public class FieldController extends AbstractManageController<FieldService, Field> {
    
    protected Logger log = Logger.getLogger(FieldController.class);
    
    @Autowired
    private FieldTemplateService templateService;
    @Autowired
    private EntityService entityService;
    @Autowired
    private TableService tableService;
    
    @RequestMapping(value = "/getTemplates", method = RequestMethod.POST)
    public void getElements(HttpServletResponse response) throws IOException {
        JsonHelper.prepareJsonResponse(Utils.convertToOptions(templateService.getAll()), response);
    }
    
    public Field prepareObject(HttpServletRequest request) throws Exception {
        Long id = getLong(request, "id");
        
        String title = request.getParameter("title");
        if(title==null || title.isEmpty()) {
            throw new Exception("Title is not specified");
        }
        
        Long templateId = getLong(request, "templateId");
        if(templateId==null) {
            throw new Exception("Field Template is not selected");
        }
        
        Long tableId = getLong(request, "tableId");
        Long entityId = getLong(request, "entityId");
        String column = request.getParameter("column");
        boolean isAttr = getBoolean(request, "attribute");
        
        FieldTemplate template = templateService.getById(templateId.longValue());
        
        Field field;
        if(id==null){
            field = new Field(title, template);
        } else {
            field = new Field(id.longValue() ,title, template);
        }
        field.setActive(getBoolean(request, "active"));
        field.setAttribute(isAttr);
        field.setEntity(entityService.getById(entityId));
        field.setColumnName(column);
        return field;
    }
    
    String getLink() {
        return MANAGE_FIELD;
    }
}
